import re

def get_id_name(info):
    transcript_id_pattern = r'transcript_id "(.*?)";'
    gene_name_pattern = r'gene_name "(.*?)";'
    transcript_id_match = re.search(transcript_id_pattern, info)
    gene_name_match = re.search(gene_name_pattern, info)
    transcript_id = transcript_id_match.group(1) if transcript_id_match else 'na'
    gene_name = gene_name_match.group(1) if gene_name_match else "na"

    # print(transcript_id, gene_name)
    return transcript_id,gene_name


with open("mm9.knownGene.gtf","r",encoding="utf8") as f:
    content = f.readlines()

output = list()
for line in content:
    line = line.strip().split('\t')
    if line[2] == "transcript":
        tid,name = get_id_name(line[8])
        output.append(
            '\t'.join([line[0],line[3],line[4],tid,name,line[6]])+"\n"
        )
with open("mm9.knownGene.bed","w",encoding="utf8",newline="") as f:
    f.writelines(output)